/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.security.MessageDigest;
import org.onlinevillage.Gbencode;

/**
 *
 * @author geoff
 */
class TorrentLoader {

    static loadTorrents() {
        ExpandoMetaClass.enableGlobally()
         Gbencode.modifyMetaClasses()

        //this needs to be configured relative to the root of the installation
        String dirname = './torrents'
         File torrentDir = new File( dirname )

        def torrentStrings = []

        torrentDir.eachFileMatch( ~/.*\.torrent$/ ) {

            String bString = new String( it.readBytes() )

            Map datastructure = bString.bdecode()
            Map info = datastructure.info
            String infoString = info.bencode()

            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(infoString.getBytes(), 0, infoString.length());
            sha1hash = md.digest();
            String infoHash = new String( sha1hash );

            def torrent = new Torrent(infoHash:infoHash, filename:it.name )
            torrent.save()

        }
    }
}

